package hedron.utils;

public class BGUtil {

	public static String currencyToWords(double value) {
		if (value == 0 || Double.isNaN(value)) {
			return "";
		}
		long longValue = (long) Math.round(value * 100d);
		StringBuffer strValue = new StringBuffer("000000000000000000");
		strValue.append(longValue);
		strValue.reverse().insert(2, '0');

		// build spelling
		StringBuffer result = new StringBuffer();

		spell(strValue, 12, "един милиард ", "милиарда ", result, false);
		spell(strValue, 9, "един милион ", "милиона ", result, false);
		spell(strValue, 6, "хиляда ", "хиляди ", result, false);
		spell(strValue, 3, "лев", "лева", result, false);

		longValue = (long) value;
		if ((value - longValue) != 0d) {
			if (longValue > 0) {
				result.append(", и ");
			}
			spell(strValue, 0, "стотинка", "стотинки", result, true);
		}
		return result.toString();
	}

	private static String[] thirdDigitSpell = { "", "сто ", "двеста ", "триста ", "четиристотин ", "петстотин ",
			"шестстотин ", "седемстотин ", "осемстотин ", "деветстотин" };
	private static String[] firstDigitSpell = { "", "един", "два", "три", "четири", "пет", "шест", "седем", "осем",
			"девет" };

	private static StringBuffer spell(StringBuffer strValue, int offset, String sufixSingular, String sufixPlural,
			StringBuffer result, boolean precision) {
		String value = strValue.substring(offset, offset + 3);
		if (!"000".equals(value)) {
			if ("100".equals(value)) {
				if (precision) {
					result.append("една ");
				}
				result.append(sufixSingular);
			} else if ("200".equals(value) && precision) {
				result.append("две ");
				result.append(sufixPlural);
			} else {
				int first = 0x0F & (int) strValue.charAt(offset);
				int second = 0x0F & (int) strValue.charAt(offset + 1);
				int third = 0x0F & (int) strValue.charAt(offset + 2);
				if (third > 0) {
					result.append(thirdDigitSpell[third]);
				}
				if (first == 0 && second > 0) {
					result.append("и ");
				}
				if (second == 1) {
					if (first > 0) {
						result.append(firstDigitSpell[first]);
						if (first == 1) {
							result.append("а");
						} else if (first > 1) {
							result.append("на");
						}
					}
					result.append("десет ");
				} else if (second > 1) {
					result.append(firstDigitSpell[second]);
					result.append("десет ");
				}
				if (second != 1 && first > 0) {
					if (second > 1 || third > 0) {
						result.append("и ");
					}
					if (first == 1 && precision) {
						result.append("една");
					} else {
						result.append(firstDigitSpell[first]);
					}
					result.append(' ');
				}
				result.append(sufixPlural);
			}
		}
		return result;
	}
}
